import { createStore } from 'vuex'

const store = createStore({
    state: {
        token: localStorage.getItem('token') || '',
        userInfo: JSON.parse(localStorage.getItem('userInfo')) || null
    },

    mutations: {
        setToken(state, token) {
            state.token = token
            localStorage.setItem('token', token)
        },

        setUserInfo(state, userInfo) {
            state.userInfo = userInfo
            localStorage.setItem('userInfo', JSON.stringify(userInfo))
        },

        clearAuth(state) {
            state.token = ''
            state.userInfo = null
            localStorage.removeItem('token')
            localStorage.removeItem('userInfo')
        }
    },

    actions: {
        login({ commit }, { token, userInfo }) {
            commit('setToken', token)
            commit('setUserInfo', userInfo)
        },

        logout({ commit }) {
            commit('clearAuth')
        }
    },

    getters: {
        isAuthenticated: state => !!state.token,
        isAdmin: state => state.userInfo?.role === 'teacher',
        isStudent: state => state.userInfo?.role === 'student'
    }
})

export default store 